<?php

namespace Home\Model;

use Think\Model;

/**
 * Description of GameModel
 * 游戏分类模型
 * @author xtceetg
 */
class GameUserRelationModel extends Model {

    protected $tablename = "game_user_relation";

    public function add_user_game_relation($uid, $username, $gid, $sid, $refer) {
        $sql = "select * from game_user_relation where uid='" . $uid . "' and game_id='" . $gid . "' and area_num='" . $sid . "'";
        if ($data = $this->query($sql)) {
            //更新操作
            $data[0]['login_times'] +=1;
            $data[0]['last_ip'] = get_client_ip();
            $data[0]['last_time'] = time();
            $this->where("uid='%d' and game_id='%d' and area_num='%d'", array($uid, $gid, $sid))->save($data[0]);
        } else {
            //添加操作
            $data['uid'] = $uid;
            $data['username'] = $username;
            $data['game_id'] = $gid;
            $data['area_num'] = $sid;
            $data['login_times'] = 1;
            $data['first_ip'] = get_client_ip();
            $data['first_time'] = time();
            $data['refer'] = $refer;
            $this->data($data)->add();
        }
    }

    public function set_last_game_cookie($uid) {
        $sql = "SELECT g.gamename,a.areaname,r.game_id,r.area_num FROM game_list AS g ,game_server_list AS a ,game_user_relation AS r WHERE r.uid='" . $uid . "' AND r.game_id=g.id AND g.id=a.game_id AND r.area_num=a.area_num ORDER BY r.login_times DESC LIMIT 3";
        $last_game = $this->query($sql);
        $temp = '';
        $sum = count($last_game);
        for ($i = 0; $i < $sum; $i++) {
            if ($sum == 1) {
                $temp.=$last_game[$i]['game_id'] . '|' . $last_game[$i]['area_num'] . '|' . $last_game[$i]['gamename'] . '|' . $last_game[$i]['areaname'];
            } else {
                $temp.=$last_game[$i]['game_id'] . '|' . $last_game[$i]['area_num'] . '|' . $last_game[$i]['gamename'] . '|' . $last_game[$i]['areaname'] . '@';
            }
        }
        cookie('last_game', $temp);  //设置cookie
    }

    public function getByRelation($username, $gid, $sid) {
        $sql = "select * from game_user_relation where username='" . $username . "' and game_id='" . $gid . "' and area_num='" . $sid . "'";
        return $this->query($sql);
    }

}
